import React from 'react';
import myNumReducer from './myNumReducer';
import myMsgReducer from './myMsgReducer';
import myCreateStore from './myCreateStore';
class MyApp extends React.Component{
    state={
        step:1,
        num:0,
        msg:'',
        msgs:[]
    }

    componentDidMount() {
        const myStore = myCreateStore(myNumReducer,this.state.num);
        myStore.subscibe(()=>this.forceUpdate());
    }

    handleClick= (evt) =>{

        const action = {type:evt.target.name,step:this.state.step};
        console.log("action....",action);
        //调用自定义store
        const myStore = myCreateStore(myNumReducer,this.state.num);
        myStore.dispatch(action);
        const num = myStore.getState();
        console.log("myStore.getState...",myStore.getState());
        this.setState({
                num:num
            })

        // const num = myReducer(this.state.num,action);
        // console.log(num);
        // this.setState({
        //     num:num
        // })
    }
    handleStepChange= (evt)=>{
        this.setState({
            msg: evt.target.value,
            step: Number(evt.target.value)
        })
    }
    handleMsgClick= (evt) =>{
        const initMsg = this.state
        const action = {type:evt.target.name,msg:this.state.msg};
        console.log("msg action....",action);
        //调用自定义store
        const myStore = myCreateStore(myMsgReducer,initMsg);
        myStore.dispatch(action);
        const m = myStore.getState();
        console.log("myStore.getState...",myStore.getState());
        this.setState({
            msgs:m.msgs
        })
    }

    handleMsgDelete =()=>{
        const action = {type:"DEL_MSG",index:1};
        //调用自定义store
        const myStore = myCreateStore(myMsgReducer,this.state.msgs);

        //执行状态监听
        const listen = ()=>{
            console.log("执行listen....",myStore.getState())
            this.setState({
                msgs:myStore.getState().msgs
            })
        }
        myStore.subscibe(listen);

        myStore.dispatch(action);
        // const m = myStore.getState();
        // this.setState({
        //     msgs:m.msgs
        // })
    }
    render() {
        return(<div>
            <input value={this.state.step} onChange={this.handleStepChange}/>
            <button name="ADD" onClick={this.handleClick}>增加+</button>
            <button name="SUB" onClick={this.handleClick}>减少-</button>
            <label>{this.state.num}</label>
            <button name="ADD_MSG" onClick={this.handleMsgClick}>发送消息</button>
            <button name="DEL_MSG" onClick={this.handleMsgDelete}>删除消息</button>
            <ul>
                {
                    this.state.msgs.map((item,index)=>{
                        return(<li key={index} onClick={this.handleMsgDelete(index)}>{item}</li>)
                    })
                }
            </ul>
        </div>)
    }
}

export default MyApp;